package com.atguigu.mq.cofig;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    //postconstruct:在ioc初始化bean对象组织向一些初始化操作
    @PostConstruct
    private void iniit(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }


    //确认模式correlationdata:关联数据,类似鱼电子邮件的附件
    //ack:  ack=true 代表交换机收到消息了;ack=false代表交换机没有收到消息(没有收到一般会重发)
    //cause: 交换机没有收到消息会给出具体的原因,收到为空
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        //如果发送数据是携带了关联数据,那么回调可以收到这个关联数据
        log.info("correlationData="+correlationData);


        log.info("ack="+ack);
        if(ack){
            log.info("交换机收到咱的消息了");
            log.info("case="+cause);
        }else {
            log.info("交换机meiyou收到咱的消息了");
            log.info("case="+cause);
        }

    }

    //退回消息:一定是队列没有收到才会退回的
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("returnedMessage="+returnedMessage);
        log.info("消息主体"+new String(returnedMessage.getMessage().getBody()));
        log.info("应答码="+returnedMessage.getReplyCode());
        log.info("描述="+returnedMessage.getReplyText());
        log.info("消息使用的交换器Exchange="+returnedMessage.getExchange());
        log.info("消息使用的路由routing="+returnedMessage.getRoutingKey());

    }
}
